﻿using AnlianCommon.Common.Domains.UserPermissions;
using AnlianCommon.Common.DTO;
using AnlianCommon.Common.Infrastructure.IRepository;
using AnlianCommon.Enum;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Security.Cryptography;
using System.Text;

namespace AnlianCommon.API.Commands.UserLogics
{
    public class UserLogicsQueryHandler : IRequestHandler<UserLogicsQueryCommand, Result>
    {
        private readonly IBaseRepository<User> _usersRepository;

        public UserLogicsQueryHandler(IBaseRepository<User> usersRepository)
        {
            _usersRepository = usersRepository;
        }
        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(UserLogicsQueryCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            try
            {
                request.UserPwd = Md5(request.UserPwd);
                var login = await(await _usersRepository.GetAll()).Where(c=>c.UserName==request.UserName&&c.UserPwd==request.UserPwd).FirstOrDefaultAsync();
                if (login != null)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data= login;
                    result.Msg = "登陆成功";
                }
                else
                {
                    result.Msg = "登陆失败";
                }
            }
            catch (Exception)
            {

                throw;
            }
            return result;  
        }
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public static string Md5(string pwd)
        {
            var md5 = MD5.Create();
            var str = md5.ComputeHash(Encoding.UTF8.GetBytes(pwd));
            return BitConverter.ToString(str).Replace("-","").ToLower();
        }
    }
}
